import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/services/api.dart';

import 'state.dart';

class MyPointsLogic extends GetxController {
  final MyPointsState state = MyPointsState();
  final RefreshController refreshController =
      RefreshController(initialRefresh: false);

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    getMemberPoints();
    getMemberPointsTurnover();
    getAdvertisingList();
  }

  /// 获取会员积分
  void getMemberPoints() {
    Map<String, dynamic> params = {"access_token": SpUtil.getString("token")};
    Api.getMemberPoints(params).listen((event) {
      print("获取会员积分的event：$event");
      if (event["code"] == 0) {
        state.memberPoints = event["point"];
        update();
      }
    });
  }

  // 获取广告
  void getAdvertisingList() {
    var params = {
      'adv_category': 6,
      'page_num': 1,
      'page_size': 10,
      'status_num_id': 3
    };
    Api.getAdvertising(params).listen((event) {
      print("广告：$event");
      if (event["code"] == 0 && event["list"] != null) {
        state.advertising = event['list'];
      } else {
        state.advertising = [];
      }
      update();
    });
  }

  /// 获取会员积分流水
  void getMemberPointsTurnover() {
    Map<String, dynamic> params = {
      "access_token": SpUtil.getString("token"),
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "cur_page": state.currentPage,
      "page_count": state.pageSize,
      // "integral_type":state.type + 1
    };

    Api.getMemberPointsTurnover(params).listen((event) {
      print("获取会员积分流水的event：$event");
      if (event["code"] == 0) {
        List list = [];
        if (state.type == 0) {
          list = event["page_model"]["data"];
        }
        if (state.type == 1) {
          list = event["page_model_used"]["data"];
        }
        if (state.type == 2) {
          list = event["page_model_passed"]["data"];
        }
        if (state.currentPage == 1) {
          if (list != null) {
            state.memberPointsTurnoverList = list;
          }
        } else {
          if (list != null) {
            state.memberPointsTurnoverList.addAll(list);
          }
        }
        if ((list == null || list.isEmpty || list.length < state.pageSize) &&
            state.memberPointsTurnoverList.length > 0) {
          refreshController.loadNoData();
        }
        update();
      }
    });
  }

  onRefresh() {
    state.currentPage = 1;
    state.memberPointsTurnoverList.clear();
    return getMemberPointsTurnover();
  }

  onLoading() async {
    state.currentPage++;
    return getMemberPointsTurnover();
  }
}
